GBML manual / Maps

map_set

Stores value at key in target, a map - inserting key if it is new, or OVERWRITING the existing value if key was already present. Returns true if target now holds key/value; false only if key was new AND target was already full (nothing is changed - target never crashes or corrupts). Overwriting an EXISTING key always succeeds, even when target is full, since it never grows target.

Syntax

map_set(target, key, value) -> bool

Arguments

NameType
targetmap
keymapkey
valueelement

Returns

bool

Description

Stores value at key in target, a map<K,V> - inserting key if it is new, or OVERWRITING the existing value if key was already present. Returns true if target now holds key/value; false only if key was new AND target was already full (nothing is changed - target never crashes or corrupts, it just stops accepting new keys). Overwriting an EXISTING key always succeeds, even when target is full, since it never grows target.

target is a real fixed-size hash table with room for N entries (keys of type K, values of type V) - N is target's own declared capacity (/// @capacity, default 8 if untagged, same rule every other container on this manual uses), and it must always be a POWER OF TWO (2, 4, 8, 16, 32, ...) - its underlying storage (a hash table) requires it. /// @capacity 10 is refused at check time, naming the nearest legal size to use instead (16); the untagged default (8) already satisfies this, so an untagged map<K,V> is never affected.

The key type K must be one GBML can hash: int, real, bool, string, color, ref<obj>, or an asset id (sprite/sound/song/font/tileset/room/path/effect). A struct cannot be used as a key - the check happens where the variable is declared, not here.

Example

/// @type {map<string,int>}
var scores = {};
var added = map_set(scores, "alice", 10); // true - there was room
var replaced = map_set(scores, "alice", 20); // true - overwriting "alice" always succeeds
A real capture - the map right after map_set(scores, "alice", 10)A real capture - the map right after map_set(scores, "alice", 10)
A real capture - the map right after map_set(scores, "alice", 10)
The same map after map_set(scores, "alice", 20) - overwritten, not a second entryThe same map after map_set(scores, "alice", 20) - overwritten, not a second entry
The same map after map_set(scores, "alice", 20) - overwritten, not a second entry

On the GBA

The hash map's insert_or_assign, guarded by contains()+full() first (see this file's own Maps group header, "OVERWRITING AN EXISTING KEY") - an unguarded insert_or_assign on a full map with a genuinely new key would abort. O(1) average.

See also: map_getmap_hasmap_removemap_lengthmap_clearData containers